<template>
	<view class="pay" v-if="all_pay_product && (!isiosapp || ios_products_init_ok)">
		<view class="wrapper">
			<view class="v_t1">
				<view v-if="userData" class="v_name">
					<text class="tt1">
						Ai用户
						<image class="ii"  v-if="userData && userData.vip_time"  src="https://sm.2sxzw.com/mgmg/jiabin01/mine/mine_vip_2.png">
						</image>
						<image v-else class="ii" src="/static/img/VIP1.png"></image>						
					</text>
					<view class="vt2">
						<text class="tt2">ID:{{ userData.uid }}</text>
					</view>
				</view>
			</view>
			<slidingBlock :list="list" @change="(event) => currentIndex = event" :curNow="currentIndex"></slidingBlock>
		</view>
		<swiper class="swiper" circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-if="list.includes('积分套餐')">
				<view class="swiper-view">
					<view class="jifen">
						<view class="jifen-item"
							v-for="(item, index) in all_pay_product.filter(item => item.trade_type == 1)" :key="index"
							:class="{ 'item_margin_left': index % 3 !== 0, 'item_margin_top': index > 2,'item_choise': index == choisePayIndexArr.Score_index}"
							@click="choisePayIndexArr.Score_index = index">
							<view class="jifen-item-price">
								<text class="aa">¥</text>
								{{item.price}}
							</view>
							<view class="jifen-item-jifen">{{item.score}}积分</view>
							<view class="jifen-item-tip" :class="{ 'hot': item.tip.includes('HOT')}">
								{{item.tip.replace("HOT","")}}
							</view>
						</view>
					</view>
				
					<view class="desc">
						<text class="title">积分用途</text> <br>
						<text>1、所有视频功能都需要积分</text> <br>
						<text>2、图片换脸通道五</text> <br>
					</view>
					<button class="pay_btn" :loading="loadding" :disabled="loadding"
						@click="onPayClick(all_pay_product.filter(item => item.trade_type == 1)[choisePayIndexArr.Score_index].pay_id)">支付¥{{all_pay_product.filter(item => item.trade_type == 1)[choisePayIndexArr.Score_index].price}}</button>
					<view class="payXieyiText">
						<radio-group @change="XieyiRadioChange">
								<label class="radio"><radio  value="r1"  :checked="isSureRadio==true" />						
								支付即同意
									<navigator url="/src/pages/My/Pay/xieyi" hover-class="navigator-hover">
									《用户协议和会员协议》
									</navigator>
								</label>
						</radio-group>
					</view>					
				</view>
			</swiper-item>
			<swiper-item v-if="list.includes('会员套餐')">
				<view class="swiper-view">
					<view class="jifen">
						<view class="jifen-item"
							v-for="(item, index) in all_pay_product.filter(item => item.trade_type == 2)" :key="index"
							:class="{ 'item_margin_left': index % 3 !== 0, 'item_margin_top': index > 2,'item_choise': index == choisePayIndexArr.Vip_index}"
							@click="choisePayIndexArr.Vip_index = index">
							<view class="jifen-item-price">
								<text class="aa">¥</text>
								{{item.price}}
							</view>
							<view class="jifen-item-jifen">
								{{ item.hours >= 24? `${item.hours/24}天` : `${item.hours}小时` }}会员
							</view>
							<view class="jifen-item-tip" :class="{ 'hot': item.tip.includes('HOT')}">
								{{item.tip.replace("HOT","")}}
							</view>
						</view>
					</view>
					
					<view class="desc">
						<text class="title">图片会员用途</text> <br>
						<text>1、图片功能不限量使用</text> <br>
						<text>2、如果使用视频功能，请购买积分，不要买错了，只购买会员不能使用视频功能</text> <br>
						<text>3、如何想不限量使用视频功能，请联系客服开通视频无限使用权限</text> <br>
					</view>
					
					<button class="pay_btn" :loading="loadding" :disabled="loadding"
						@click="onPayClick(all_pay_product.filter(item => item.trade_type == 2)[choisePayIndexArr.Vip_index].pay_id)">支付¥{{all_pay_product.filter(item => item.trade_type == 2)[choisePayIndexArr.Vip_index].price}}</button>
					<view class="payXieyiText">
						<radio-group @change="XieyiRadioChange">
								<label class="radio"><radio  value="r1"  :checked="isSureRadio==true" />						
								支付即同意
									<navigator url="/src/pages/My/Pay/xieyi" hover-class="navigator-hover">
									《用户协议和会员协议》
									</navigator>
								</label>
						</radio-group>
					</view>						
				</view>
			</swiper-item>
			<swiper-item v-if="list.includes('组合套餐')">
				<view class="swiper-view">
					<view class="jifen">
						<view class="jifen-item" style="height: 249rpx;"
							v-for="(item, index) in all_pay_product.filter(item => item.trade_type == 3)" :key="index"
							:class="{ 'item_margin_left': index % 3 !== 0, 'item_margin_top': index > 2,'item_choise': index == choisePayIndexArr.Combine_index}"
							@click="choisePayIndexArr.Combine_index = index">
							<view class="jifen-item-price">
								<text class="aa">¥</text>
								{{item.price}}
							</view>
							<view class="zuhe">
								<view class="jifen-item-jifen" style="margin-top: 0;">
									{{ item.hours >= 24? `${item.hours/24}天` : `${item.hours}小时` }}会员
								</view>
								<view class="jifen-item-jifen" style="margin-top: 10rpx;">{{item.score}}积分</view>

							</view>

							<view class="jifen-item-tip" :class="{ 'hot': item.tip.includes('HOT')}">
								{{item.tip.replace("HOT","")}}
							</view>

						</view>
					</view>
					
					<!-- 添加用户同意协议 勾选了之后才能点击支付  不然不能选择支付 -->
					
					<button class="pay_btn" :loading="loadding" :disabled="loadding"
						@click="onPayClick(all_pay_product.filter(item => item.trade_type == 3)[choisePayIndexArr.Combine_index].pay_id)">支付¥{{all_pay_product.filter(item => item.trade_type == 3)[choisePayIndexArr.Combine_index].price}}</button>
					<view class="payXieyiText">
						<radio-group @change="XieyiRadioChange">
								<label class="radio"><radio  value="r1"  :checked="isSureRadio==true" />						
								支付即同意
									<navigator url="/src/pages/My/Pay/xieyi" hover-class="navigator-hover">
									《用户协议和会员协议》
									</navigator>
								</label>
						</radio-group>
					</view>						
				</view>
			</swiper-item>
		</swiper>
		
		
		<uni-popup ref="popup" type="bottom" border-radius="20px 20px 0 0">
			<view class="popupXieyi">
				<uni-icons class="closepopUp" @click="closePOPIcon" type="closeempty" color="#333" size="24"></uni-icons>
				<view style="font-size:30rpx;text-align: center;margin-top:40rpx;">
					我已阅读并同意 
					<navigator style="color:#000;font-weight: 700;" url="/src/pages/My/Pay/xieyi" hover-class="navigator-hover">
									《用户协议和会员协议》
									</navigator>
								确认开通
				</view>				
				<button size="default" type="default" @click="closePOP">继续</button>
			</view>
		</uni-popup>
	</view>
	<view v-else class="fei_pay">
		<image class="fei_image" :src="gong_link" mode="aspectFit" v-if="gong_link" @click="preview_image(gong_link)"></image>
		<text class="fei_text" v-else>{{tip}}</text>
	</view>
</template>

<script>
	import slidingBlock from './slidingBlock.vue';
	import {
		iospay,
		huanlianwxminipay,
		huanlianaliminipay,
		PayProduct
	} from '@/src/api/huanlian.js';
	import {
		Iap
	} from '@/src/utils/iap.js';
	import {
		getUser
	} from '@/src/utils/utils.js';
	export default {
		components: {
			slidingBlock,
		},
		data() {
			return {
				userData: null,
				currentIndex: null,
				list: [],
				loadding: false,
				choisePayId:null,
				_iap: null,
				platform: null,
				all_pay_product: null,
				isSureRadio:false,
				// 支付相关的信息
				choisePayIndexArr: {
					Score_index: 0,
					Vip_index: 0,
					Combine_index: 0,
					limitTime_index: 0,
				},
				isiosapp: false,
				ios_products_init_ok: false, // iOSapp对支付项目是否初始化完成
				gong_link: null, // 公众号二维码链接
				tip: ""
			};
		},

		onLoad(options) {
			this.init()
			this.currentIndex = options.currentIndex;
			this.getPayProduct();
			this.initUserData()
		},

		methods: {
			swiperChange(event){
				this.currentIndex = event.detail.current;
			this.isSureRadio=false;
			},
			popupOpen(){
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('bottom')
			},
			closePOP(){
				this.$refs.popup.close();				
				this.isSureRadio=true;	`	`
			},
			closePOPIcon(){
				this.$refs.popup.close();		
			},
			async initUserData() {
				let _this = this;
				this.userData = getApp().globalData.userData;
				if (!this.userData && uni.getStorageSync('jwt_token')) {
					await getUser();
					this.userData = getApp().globalData.userData;
				}
				uni.$on('userUpdate', (d) => {
					_this.userData = d.userData;
				});
			},
			init() {
				// #ifdef APP
				if (getApp().globalData.platform == 'ios') {
					this.isiosapp = true
					uni.$on('getProduct', () => {
						this.ios_products_init_ok = true
					});
				}
				// #endif
			},
			async getPayProduct() {
				try {
					let _this = this;
					let res = await PayProduct();
					this.all_pay_product = res.data.pay_product
					this.gong_link = res.data.gong_link	
					//写死 等支付搞好了删除
					//this.gong_link = "https://sm.2sxzw.com/media/admin_file/1/bin.jpg"
				
					this.tip = res.data.tip
					if (this.all_pay_product && this.all_pay_product.length > 0) {
						if (this.all_pay_product.some((item) => item.trade_type === 1)) {
							this.list.push('积分套餐');
						}
						if (this.all_pay_product.some((item) => item.trade_type === 2)) {
							this.list.push('会员套餐');
						}
						if (this.all_pay_product.some((item) => item.trade_type === 3) || this.all_pay_product.some((item) => item
								.trade_type ===
								4)) {
							this.list.push('组合套餐');
						}
						this.initIap(this.all_pay_product.map(item => item.pay_id))
					}
				} catch (e) {
					console.error(e, e.errMsg);
				}
			},
			initIap(products) {
				// #ifdef APP
				if (getApp().globalData.platform == 'ios') {
					let _this = this;
					this._iap = new Iap({
						products: products,
						upResut: _this.validatePaymentResult,
						createPayOrder: _this.createPayOrder,
						onPaySucess: _this.onPaySucess,
						endLoadding: _this.endLoadding,
					});
				}
				// #endif
			},
			onPayClick(choisePayId) {				
				if(!this.isSureRadio){
					// 先注释
					this.popupOpen()
					return;
				}
						
				this.choisePayId = choisePayId
				this.loadding = true;
				
				// #ifdef APP
				if (getApp().globalData.platform == 'ios') {
					this._iap.pay(choisePayId);
				} else {
					this.onWxMiniPay(1, choisePayId);
				}
				// #endif
				// #ifdef MP-WEIXIN
				this.onWxMiniPay(2, choisePayId);
				// #endif
				// #ifdef MP-ALIPAY
				this.onAliMiniPay(choisePayId);
				// #endif
			},
			XieyiRadioChange(event ){
				this.isSureRadio=true;
			},
			async onAliMiniPay(choisePayId) {
				try {
					let res = await huanlianaliminipay({
						choisePayId: choisePayId,
					});
					let [fail, success] = await uni.requestPayment({
						orderInfo: res.data,
					});
					if (fail) {
						if (fail.errMsg == 'requestPayment:fail cancel'){
							this.$showToast('支付取消');
						}else{
							this.$showToast('支付失败');
						}
					} else if (success.resultCode == '6001') {
						this.$showToast('支付取消');
					} else {
						this.$showToast('支付成功');
						let result = await getUser({}, true);
						// this.userData = result;
					}
					console.log(fail, success);
				} catch (e) {
					console.error(e, e.errMsg);
				} finally {
					this.loadding = false;
				}
			},
			async onWxMiniPay(plat, choisePayId) {
				this.loadding = true;
				try {
					let res = await huanlianwxminipay({
						choisePayId: choisePayId,
					});
					let data = null;
					if (plat == 1) {
						// anroid 微信支付
						data = {
							provider: 'wxpay',
							orderInfo: res.data,
						};
					} else {
						// 微信小程序支付
						data = res.data;
					}
					let [fail, success] = await uni.requestPayment(data);
					if (fail) {
						if (fail.errMsg == 'requestPayment:fail cancel') {
							this.$showToast('支付取消');
						} else {
							console.log(fail);
						}
						this.$showToast('支付失败');
					} else {
						// this.$showToast('支付成功')
						uni.showModal({
							showCancel: false,
							content: '支付成功',
						});
						getUser({}, true);
					}
					console.log(fail, success);
				} catch (e) {
					console.error(e, e.errMsg);
				} finally {
					this.loadding = false;
				}
			},
			onRestoreClick() {
				if (this._iap) this._iap.restore();
			},
			endLoadding() {
				this.loadding = false;
			},
			async createPayOrder() {
				let _this = this;
				const res = await iospay({
					choisePayId: _this.choisePayId,
				});
				return res;
			},
			async validatePaymentResult(data) {
				try {
					const res = await iospay(data);
					// console.log(res)
					if (res.err_no == 0) {
						this.$showToast('支付成功');
						return;
					} else if (res.err_no == 3) {
						throw new Error('支付后网络异常');
					} else if (res.err_no != 2) {
						throw new Error('支付后网络异常');
					}
				} catch (err) {
					uni.showModal({
						showCancel: false,
						content: err.errMsg,
					});
					console.log(err, err.errMsg);
					// throw err;
				}
			},
			async onPaySucess() {
				getUser({}, true);
			}
		},
	};
</script>

<style lang="scss">
	@import 'pay.scss';
</style>